import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import api from '../api/api'

export const useTaskStore = defineStore('task', () => {
  // 任务数据
  const tasks = ref([])

  // 筛选条件
  const statusFilter = ref('all')
  const priorityFilter = ref('all')
  const categoryFilter = ref('all')
  
  // 是否显示任务表单
  const showTaskForm = ref(false)
  
  // 当前编辑的任务
  const editingTask = ref(null)

  // 统计信息
  const stats = computed(() => {
    return {
      total: tasks.value.length,
      pending: tasks.value.filter(t => t.status === 'pending').length,
      inProgress: tasks.value.filter(t => t.status === 'in-progress').length,
      completed: tasks.value.filter(t => t.status === 'completed').length
    }
  })

  // 筛选后的任务
  const filteredTasks = computed(() => {
    return tasks.value.filter(task => {
      const statusMatch = statusFilter.value === 'all' || task.status === statusFilter.value
      const priorityMatch = priorityFilter.value === 'all' || task.priority === priorityFilter.value
      const categoryMatch = categoryFilter.value === 'all' || task.category === categoryFilter.value
      
      return statusMatch && priorityMatch && categoryMatch
    })
  })

  // 加载任务列表
  async function fetchTasks() {
    try {
      const res = await api.getTasks()
      // 兼容后端返回格式
      if (res.data && Array.isArray(res.data.data)) {
        tasks.value = res.data.data
      } else if (Array.isArray(res.data)) {
        tasks.value = res.data
      }
    } catch (e) {
      console.error('获取任务失败', e)
    }
  }

  // 初始化时加载任务
  fetchTasks()

  // 添加任务
 async function addTask(task) {
  try {
    const response = await api.createTask(task);
    this.tasks.push(response.data); // 把新任务加入状态中
    return response.data;
  } catch (error) {
    console.error('创建任务失败:', error);
    throw error;
  }
  }

  // 更新任务
async function updateTask(id, task) {
  try {
    const response = await api.updateTask(id, task)

    // 更新本地状态：找到对应任务并替换为新数据
    const index = tasks.value.findIndex(t => t.id === id)
    if (index !== -1) {
      tasks.value[index] = response.data
    }

    return response.data
  } catch (error) {
    console.error('更新任务失败:', error)
    throw error
  }
}

  // 删除任务
  async function deleteTask(id) {
    try {
      await api.deleteTask(id)
      tasks.value = tasks.value.filter(task => task.id !== id)
      return true
    } catch (e) {
      console.error('删除任务失败', e)
      throw e
    }
  }

  // 切换任务状态
  async function toggleTaskStatus(id, status) {
    try {
      await api.updateTaskStatus(id, status)
      const task = tasks.value.find(t => t.id === id)
      if (task) task.status = status
    } catch (e) {
      console.error('更新任务状态失败', e)
      throw e
    }
  }

  // 设置筛选条件
  function setFilter(type, value) {
    if (type === 'status') statusFilter.value = value
    if (type === 'priority') priorityFilter.value = value
    if (type === 'category') categoryFilter.value = value
  }

  // 准备编辑任务
  function prepareEditTask(task) {
    editingTask.value = { ...task }
    showTaskForm.value = true
  }

  return {
    tasks,
    filteredTasks,
    stats,
    statusFilter,
    priorityFilter,
    categoryFilter,
    showTaskForm,
    editingTask,
    addTask,
    updateTask,
    deleteTask,
    toggleTaskStatus,
    setFilter,
    prepareEditTask,
    fetchTasks
  }
})